package dao

import (
	"context"
	"errors"
	"fresh-e-commerce/global"
	"fresh-e-commerce/pkg"
	"go.uber.org/zap"
	"math/rand"
	"strconv"
	"time"
)

func UserSms(mobile string, source string) (err error) {
	if len(mobile) != 11 {
		return errors.New("手机号码长度为十一位")
	}
	code := strconv.Itoa(rand.Intn(9000) + 1000)
	sms, err := pkg.Sms(mobile, code)
	if *sms.Body.Code != "OK" {
		zap.Error(err)
		return errors.New(*sms.Body.Message)
	}
	err = global.Rdb.Set(context.Background(), "sms_"+source+mobile, code, time.Minute*5).Err()
	if err != nil {
		return errors.New("验证码存储缓存失败")
	}
	return nil
}
